<?php

namespace App\Api\Http\Controllers\weixin\In;

use App\Admin\Eloquent\ProjectProfit;
use App\Api\Eloquent\Projects;
use App\Eloquent\TradeRecords;
use Ibeibeili\SinaPay\Facades\QueryBalance;
use App\Admin\Eloquent\Code;
use App\Admin\Eloquent\GiftReceive;
use App\Api\Eloquent\ProjectsUser;
use App\Api\Eloquent\Role;
use App\Api\Eloquent\User;
use Illuminate\Http\Request;
use App\Api\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use DB;
use Ibeibeili\SinaPay\Facades\QueryIsSetPayPassword;
use Ibeibeili\SinaPay\Facades\CreateBatchHostingPayTrade;
use App\Admin\Eloquent\GiftActivity;
use App\Admin\Eloquent\Project;
/*
 * 个人中心
 */
class MenuController extends Controller
{
    /*
     * 个人中心——首页
     */
    public function index(Request $request){
        $user=User::user();
        //是否注册后第一次进入个人中心，显示注册送红包
        if(Cache::has('api'.$user->phone_number)){
            $user->R_gift=Cache::pull('api'.$user->phone_number);
        }
        else{
            $user->R_gift=false;
        }
        //是否有真实姓名，有则显示，没有则显示用户名
        if(!empty($user->userInfo->name)){
            $user->ledname=$user->userInfo->name;
        }
        elseif(!empty($user->username)){
            $user->ledname=$user->username;
        }
        else{
            $user->ledname=$user->phone_number;
        }
        //如果本地未设置支付密码
        if($user->userInfo->is_set_pay_password==0){
            $pay_password_result= QueryIsSetPayPassword::send(['identity_id' => $user->identity_id, 'identity_type' => 'UID']);
            //如果sinna已设置支付密码
            if($pay_password_result['is_set_paypass'] == 'Y') {
                //发放激活红包且改变本地状态
                try{
                    //发放现金红包
                    DB::beginTransaction();
                    $active_gift=new GiftActivity();
                    $active_gift->sendGift('gift_grant_rule_7',$user->id);
                    $user->userInfo->is_set_pay_password = 1;
                    $user->userInfo->set_pay_password_time = date('Y-m-d H:i:s');
                    $user->userInfo->save();
                    //发起还款
                    $user_profit_list=ProjectProfit::where('type','=','2')
                        ->where('user_id','=',$user->id)//对应的用户
                        ->where('input_time','<=',date('Y-m-d H:i:s'))//应还款时间小于当前时间
                        ->whereNull('pay_time')//实际还款时间为空
                        ->where('status','=','0')//状态为未还款
                        ->get();
                    $num=$user_profit_list->count();
                    if($num!=0){
                        $user_project_profit=$user_profit_list->groupBy('project_id')->keyBy('project_id');
                        $project_ids=array();
                        foreach( $user_project_profit as $project_id){
                            $project_ids[]=$project_id->project_id;
                        }
                        $financier_id=Project::whereIn('id',$project_ids)->select('financier_id')->groupBy('id');
                        foreach($user_profit_list as $key=> $item){
                            $tread_list['tread_id']=createSn();//订单号
                            $tread_list['user_id']=$user->identity_id;
                            $tread_list['user_type']='UID';//用户ID
                            $tread_list['grant_type']='SAVING_POT';//账户类型(存钱罐)
                            $tread_list['money']=$item->profit+$item->money;//金额
                            $tread_list['list_data']='';//分账信息列表
                            $tread_list['mark']='代收还款金';//摘要
                            $to_tread_list[$key]=implode('~',$tread_list);

                            $records=new TradeRecords([
                                'type'=>3,
                                'project_id'=>$item->project_id,
                                'sn'=>$tread_list['tread_id'],
                                'pay_user'=>$financier_id[$item->project_id]['0'],
                                'remarks'=>'代收还款金',
                                'receive_user'=>$user->id,
                                'money'=>$tread_list['money'],
                                'created_at'=>date('Y-m-d H:i:s'),
                            ]);
                            $records->save();
                        }
                        $to_tread_list=implode('$',$to_tread_list);
                        $data=[
                            'out_pay_no'=>createSn(),
                            'out_trade_code'=>'2002',
                            'trade_list'=>$to_tread_list,
                            'notify_method'=>'single_notify',
                            'notify_url'=>$this->getNowUrl().'/return/payment',
                        ];
                        $result=CreateBatchHostingPayTrade::send($data);
                        if($result['response_code']!='APPLY_SUCCESS'){
                            empty($result['response_message']) && $result['response_message']='系统繁忙,请稍后再试';
                            throw new Exception($result['response_message']);
                        }
                    }
                    DB::commit();
                }catch(\Exception $e){
                    DB::rollback();
                    return $this->my_jsonp($request->input('callback'),'',600,$e->getMessage());
                }
            }
        }
        $user_roles=Role::getrole($user->id);
        $user->role=$user_roles;
        $params['identity_id']=$user->identity_id;
        $params['identity_type']='UID';
        $params['account_type']='SAVING_POT';
        $result=QueryBalance::send($params);
        if($result['response_code']=='NO_BASIC_ACCOUNT'){
            $user->money='0.00';//余额
            $user->profit='0.00';//累计收益
            $user->willcorpus='0.00';//待收本金
            $user->willprofit='0.00';//待收收益
            $user->frostmoney='0.00';//冻结金额
            $user->bonus='0.00';
        }
        elseif($result['response_code']!='APPLY_SUCCESS'){
            return $this->my_jsonp($request->input('callback'),'',600,$result['response_message']);
        }
        else{
            $user->money=$result['available_balance'];//可用余额
            $bonus=explode('^',$result['bonus']);
            $user->bonus=number_format($bonus['2'],2);//存钱罐总收益
        }
        $user_profit=ProjectProfit::where('user_id','=',$user->id)->get();
        $user_profit=$user_profit->groupBy('status');
        $user->profit=empty($user_profit['1'])?'0.00':number_format(collect($user_profit['1'])->sum('profit'),2);//累计收益
        if(!empty($user_profit['0'])){
            $user_willcorpus=collect($user_profit['0'])->sum('money');//待收本金
            $user_willprofit=collect($user_profit['0'])->sum('profit');//待收收益
        }
        else{
            $user_willcorpus=0;//待收本金
            $user_willprofit=0;//待收收益
        }
        $user->willcorpus=number_format($user_willcorpus,2);//待收本金
        $user->willprofit=number_format($user_willprofit,2);//待收收益
        $user->frostmoney=number_format( $user->money+$user_willcorpus+$user_willprofit,2);//持有资产
        $user->money=number_format($user->money,2);
        return $this->my_jsonp($request->input('callback'),$user);
    }
    /*
     * 我的项目
     */
    public function myProjects(Request $request ,$num,$page){
        $user=User::user();
        $id=$user->id;
        $a=5;
        $profit_list=array();
        if($num==0){
            $status=array('rush','full');
            $user_projects=ProjectsUser::join('projects','projects.id','=','projects_user.projects_id')
                ->where('projects_user.user_id','=',$id)
                ->whereIn('projects.status',$status)
                ->orderBy('invest_time','desc')
                ->skip($a*$page)
                ->take($a)
                ->select('projects_user.*','projects.status','projects.profits_cate','projects.projects_name','projects.auto_rate')
                ->get();
            foreach($user_projects as $key=> $project){
                $profit_list[$key]['list']=null;
                $profit_list[$key]['project_id']=$project->projects_id;
                $profit_list[$key]['expected_return']=number_format($project->expected_return,2);
                $profit_list[$key]['projects_name']=$project->projects_name;
                $profit_list[$key]['rate']=$project->auto_rate;
                $profit_list[$key]['invest_money']=number_format($project->invest_money,2);
                $profit_list[$key]['invest_time']=substr($project->invest_time,0,10);
                $profit_list[$key]['status']=$project->status;
            }
        }
        else{
            switch($num){
                case 1:
                    $status='payment';//还款中
                    break;
                case 2:
                    $status='finish';//还款完成
                    break;
            }
            $project_list=ProjectsUser::join('projects','projects.id','=','projects_user.projects_id')
                ->where('projects_user.user_id','=',$id)
                ->where('projects.status','=',$status)
                ->orderBy('projects_user.invest_time','desc')
                ->skip(5*$page)
                ->take(5)
                ->select('projects_user.id','projects_user.invest_money','projects_user.invest_time','projects.projects_name','projects.auto_rate','projects_user.projects_id','projects_user.expected_return')
                ->get();


            foreach($project_list as $key=> $project){
                $profit_list[$key]['list']=ProjectProfit::join('projects','projects.id','=','project_profits.project_id')
                    ->join('projects_user','projects_user.id','=','project_profits.project_user_id')
                    ->where('project_profits.project_user_id','=',$project->id)
                    ->where('project_profits.user_id','=',$id)
                    ->where('project_profits.project_id','=',$project->projects_id)
                    ->where('project_profits.type','=','1')
                    ->where('projects.status','=',$status)
                    ->select('project_profits.*')
                    ->get();

                $profit_list[$key]['project_id']=$project->projects_id;
                $profit_list[$key]['expected_return']=number_format($project->expected_return,2);
                $profit_list[$key]['projects_name']=$project->projects_name;
                $profit_list[$key]['rate']=$project->auto_rate;
                $profit_list[$key]['invest_money']=number_format($project->invest_money,2);
                $profit_list[$key]['invest_time']=substr($project->invest_time,0,10);
                $profit_list[$key]['status']=$status;
            }
        }

//        if($num==0){
//            if($page==0){
//                $project['cate']='0';//投资中
//                $project['projects_name']='企业贷(AFEHUAN007)';
//                $project['profit']='15.87';
//                $project['rate']='12.0%';
//                $project['invest_money']='500.00';
//                $project['invest_time']='2016-04-24';
//                $projects=array($project,$project,$project,$project,$project);
        $lists=view('api.myProjects',compact('profit_list'))->__toString();

        return $this->my_jsonp($request->input('callback'),compact('lists'));
    }
    /*
     * gift_receives
     */
    public function gift(Request $request,$num,$page){
        $user=User::user();
        $id=$user->id;
        $codes=Code::where('type_id','like','%'.'gift'.'%')
            ->get();
        foreach($codes as $code){
            $code_list[$code->type_id][$code->code]=$code;
        }
        $a=8;
        //红包管理-可用-
        if($num==0){
            $gifts=GiftReceive::join('gift_activities','gift_activities.id','=','activity_id')
                ->where('user_id','=',$id)
                ->where('gift_receives.end_time','>=',date('Y-m-d H:i:s'))
                ->whereNull('gift_receives.use_time')
                ->select('gift_activities.name','gift_activities.used_rule','gift_activities.used_rule_money','gift_activities.type_id','gift_receives.*')
                ->orderBy('input_time','desc')
                ->skip($page*$a)
                ->limit($a)
                ->get();
//            return view('api.gift',compact('gifts','code_list'));
            $R_list= view('api.gift',compact('gifts','code_list'))->__toString();
        }
        //红包管理-已用-
        elseif($num==1){
            $gifts=GiftReceive::join('gift_activities','gift_activities.id','=','activity_id')
                ->where('user_id','=',$id)
                ->whereNotNull('gift_receives.use_time')
                ->select('gift_activities.name','gift_activities.used_rule','gift_activities.used_rule_money','gift_activities.type_id','gift_receives.*')
                ->orderBy('input_time','desc')
                ->skip($page*$a)
                ->limit($a)
                ->get();
//            return view('api.usegift',compact('gifts','code_list'));
            $R_list= view('api.usegift',compact('gifts','code_list'))->__toString();
        }
        //红包管理-过期-
        elseif($num==2){
            $gifts=GiftReceive::join('gift_activities','gift_activities.id','=','activity_id')
                ->where('user_id','=',$id)
                ->where('gift_receives.end_time','<=',date('Y-m-d H:i:s'))
                ->select('gift_activities.name','gift_activities.used_rule','gift_activities.used_rule_money','gift_activities.type_id','gift_receives.*')
                ->orderBy('input_time','desc')
                ->skip($page*$a)
                ->limit($a)
                ->get();
//            return view('api.oldgift',compact('gifts','code_list'));
            $R_list=view('api.oldgift',compact('gifts','code_list'))->__toString();
        }
        return $this->my_jsonp($request->input('callback'),compact('R_list'));
    }
    /*
     * 交易明细
     */
    public function tradeMoney(Request $request,$num,$page){
        $user=User::user();
        switch($num){
            //分润,投资,还款
            case 0:
                $type=array(1,2,7,3,6);
                break;
            //充值
            case 1:
                $type=array(4);
                break;
            //提现
            case 2:
                $type=array(5);
                break;
        }
        $a=10;

        $user_trade_records=TradeRecords::whereIn('type',$type)
            ->where(function($query) use ($user){
                $query->where('pay_user','=',$user->id)
                    ->orWhere('receive_user','=',$user->id);
            })
            ->orderBy('created_at','desc')
            ->skip($a*$page)
            ->take($a)
            ->get();
        $R_list=null;
        if($user_trade_records->count()>0){
            foreach ($user_trade_records as $key=> $user_trade_record) {
                $list=array();
                switch ($user_trade_record->type) {
                    case 1:
                        $list['cate'] = 'in';
                        $list['name'] = '倍倍利分润';
                        break;
                    case 2:
                        $list['cate'] = 'out';
                        $list['name'] = '投资-'.Projects::where('id', '=', $user_trade_record->project_id)->value('projects_name');
                        break;
                    case 3:
                        $list['cate'] = 'in';
                        $list['name'] = '还款-'.Projects::where('id', '=', $user_trade_record->project_id)->value('projects_name');
                        break;
                    case 7:
                        $list['cate'] = 'out';
                        $list['name'] = '投资红包-'.Projects::where('id', '=', $user_trade_record->project_id)->value('projects_name');
                        break;
                    case 6:
                        $list['cate'] = 'in';
                        $list['name'] = '现金红包';
                        break;
                    case 4:
                        $list['cate'] = 'in';
                        $first_name = substr_replace($user->userInfo->bank_card_number, '***', 6, -4);
                        $last_name = Code::where('type_id', '=', 'bank_code')->where('code', '=', $user->userInfo->bank_code)->value('name');
                        $list['name'] = $first_name . '(' . $last_name . ')';
                        break;
                    case 5:
                        $list['cate'] = 'out';
                        $first_name = substr_replace($user->userInfo->bank_card_number, '***', 6, -4);
                        $last_name = Code::where('type_id', '=', 'bank_code')->where('code', '=', $user->userInfo->bank_code)->value('name');
                        $list['name'] = $first_name . '(' . $last_name . ')';
                        break;
                }
                $list['money'] = $user_trade_record->money;//money
                $list['time'] = $user_trade_record->created_at;//交易时间
                //交易状态(1,成功;2,失败;3,待完成)
                if ($user_trade_record->status == 0) {
                    $list['status'] = '3';
                } elseif ($user_trade_record->status == 1 or $user_trade_record->status == 3 ) {
                    $list['status'] = '1';
                } elseif ($user_trade_record->status == -1 or $user_trade_record->status == 2) {
                    $list['status'] = '2';
                }
                $lists[$key] = $list;
            }
            $R_list=view('api.payout',compact('lists'))->__toString();
        }
        return $this->my_jsonp($request->input('callback'),compact('R_list'));
    }
    /*
     * 经济人-客户管理
     */
    public function AgentUser(Request $request,$page){
        $user=User::user();
        $invite_code=$user->userInfo->invite_code;
        if(!$user->hasRole('Agent')&& $invite_code!=$user->userInfo->second_broker_code){
            return $this->my_jsonp($request->input('callback'),'',600,'不具备对应的权限');
        }

        $a=12;
//        $invite_code='3FREE4';
        if($invite_code!=$user->userInfo->second_broker_code){
            $user_list=User::join('user_info','user_info.user_id','=','users.id')
//                ->where('user_info.invite_code','<>',$invite_code)
                ->where('user_info.broker_code','=',$invite_code)
                ->orderBy('users.created_at','desc')
                ->get();
        }else{
            $user_list=User::join('user_info','user_info.user_id','=','users.id')
//                ->where('user_info.invite_code','<>',$invite_code)
                ->where('user_info.second_broker_code','=',$invite_code)
                ->orderBy('users.created_at','desc')
                ->get();
        }
        $data['num']=$user_list->count();
        $data['page']=$page;
        $user_list=$user_list->slice($a*$page,$a);
        $r_user_list=array();
        foreach($user_list as $to_user){
            $r_user['id']=$to_user->id;
            if($to_user->name_verified==1){
                $r_user['show_name']=$to_user->name;
            }
            elseif($to_user->phone_number_verified==1){
                $r_user['show_name']=$to_user->phone_number;
            }
            elseif($to_user->username){
                $r_user['show_name']=$to_user->username;
            }
            $r_user_list[]=$r_user;
        }
//        return view('api.agent_user',compact('r_user_list','num'));
       $content= view('api.agent_user',compact('r_user_list','data'))->__toString();
        return $this->my_jsonp($request->input('callback'),compact('content'));
    }
    /*
     * 经济人-客户详情
     */
    public function AgentUserDtail(Request $request,$id){
        $user=User::user();
        if(!$user->hasRole('Agent') &&$user->userInfo->invite_code!=$user->userInfo->second_broker_code){
            return $this->my_jsonp($request->input('callback'),'',600,'不具备对应的权限');
        }
        $to_user=User::where('id','=',$id)->first();
        $r_user=array();
        $r_user['username']=empty($to_user->username)?'无':$to_user->username;
        if($to_user->userInfo->name_verified==1){
            $r_user['verified']='已实名认证';
//            $lastname = mb_substr($to_user->userInfo->name ,0, 1, 'utf-8');
//            $firstname = mb_substr($to_user->userInfo->name, 1, 10, 'utf-8');
//            $length=mb_strlen($firstname,'utf-8');
//            $str = null;
//            for ($i = 0; $i < $length; $i++) {
//                $str .='*';
//            }
//            $r_user['name']=$lastname.$str;
            $r_user['name']=$to_user->userInfo->name;
            $r_user['id_card']=$to_user->userInfo->id_card;
        }
        else{
            $r_user['verified']='未实名认证';
            $r_user['name']='-';
            $r_user['id_card']='-';
        }
        $r_user['phone_number']=$to_user->phone_number_verified==1?$to_user->phone_number:'-';
        $r_user['email']=$to_user->email_verified==1?$to_user->email:'-';
//        return view('api.agent_user_detail',compact('r_user'));
        $content=view('api.agent_user_detail',compact('r_user'))->__toString();
        return $this->my_jsonp($request->input('callback'),compact('content'));
    }
    /*
     * 经济人-业务管理
     */
    public function AgentWork(Request $request,$page){
        $user=User::user();
        if(!$user->hasRole('Agent')&&$user->userInfo->invite_code!=$user->userInfo->second_broker_code){
            return $this->my_jsonp($request->input('callback'),'',600,'不具备对应的权限');
        }
        $a=8;
        if($user->userInfo->invite_code!=$user->userInfo->second_broker_code){
            $money_list=ProjectProfit::where('user_id','=',$user->id)
                ->where('type','2')
                ->where('status','=','1')
                ->where('role_slug','=','Agent')
                ->get();
            $money=$money_list->sum('money');
            $list=DB::table('projects_user')
                ->leftJoin(DB::raw("(select *  FROM `project_profits` WHERE `role_slug` = 'Agent' AND `type` ='2') as a "),'a.project_user_id','=','projects_user.id')
                ->join('projects','projects.id','=','projects_user.projects_id')
                ->join('codes','codes.code','=','projects.status')
                ->where('projects_user.broker_code','=',$user->userInfo->invite_code)
                ->orderBy('projects_user.invest_time','desc')
                ->select('projects_user.invest_money','projects_user.user_name','a.money','projects_user.invest_time','projects.projects_name','codes.name')
                ->skip($a*$page)
                ->take($a)
                ->get();
        }else{
            $money_list=ProjectProfit::where('user_id','=',$user->id)
                ->where('type','2')
                ->where('status','=','1')
                ->where('role_slug','=','User')
                ->get();
            $money=$money_list->sum('money');
            $list=DB::table('projects_user')
                ->leftJoin(DB::raw("(select *  FROM `project_profits` WHERE `role_slug` = 'User' AND `type` ='2') as a "),'a.project_user_id','=','projects_user.id')
                ->join('projects','projects.id','=','projects_user.projects_id')
                ->join('codes','codes.code','=','projects.status')
                ->where('projects_user.second_broker_code','=',$user->userInfo->invite_code)
                ->orderBy('projects_user.invest_time','desc')
                ->select('projects_user.invest_money','projects_user.user_name','a.money','projects_user.invest_time','projects.projects_name','codes.name')
                ->skip($a*$page)
                ->take($a)
                ->get();
        }
        $lists=array();
        foreach($list as $item){
            $r_list['user_name']=$item->user_name;
            $r_list['invest_money']=number_format($item->invest_money,2);
            $r_list['money']=number_format($item->money,2);
            $r_list['projects_name']=$item->projects_name;
            $r_list['invest_time']=substr($item->invest_time,0,10);
            $r_list['status_name']=$item->name;
            $lists[]=$r_list;
        }
        $money=number_format($money,2);
//
//            $list['name']='张一';
//            $list['invite_money']='100.00';
//            $list['money']='10.00';
//            $list['project_name']='装饰工程公司抵押贷10万';
//            $list['time']='2016-03-24';
//            $lists=array($list,$list,$list,$list,$list,$list,$list,$list);

//        return view('api.agent_work',compact('lists'));
        $content=view('api.agent_work',compact('lists'))->__toString();
        return $this->my_jsonp($request->input('callback'),compact('content','money'));
    }
    /*
     * 经济人-二级经纪人管理
     */
    public function secondAgent(Request $request,$page){
        $user=User::user();

        if(!$user->hasRole('Agent')){
            return $this->my_jsonp($request->input('callback'),'',600,'不具备对应的权限');
        }
        $list=DB::select("SELECT a.username,a.username,a.phone_number,a.name,a.invite_code,a.created_at,b.valid_num,c.use_money,d.invite_money,e.return_money FROM
		(SELECT `user_info`.`created_at`,`user_info`.`invite_code`,`users`.`username`,`users`.`phone_number`,`user_info`.`name`FROM `user_info` LEFT JOIN `users` on `user_info` .`user_id`=`users`.`id` WHERE `user_info`.`invite_code`=`user_info`.`second_broker_code` AND `user_info`.`broker_code` = '".$user->userInfo->invite_code."') a LEFT JOIN
		(SELECT COUNT(g.user_id)  AS 'valid_num', g.`second_broker_code` FROM (select `project_profits`.*, `user_info`.`second_broker_code`from `project_profits` LEFT JOIN `user_info` ON `user_info`.`user_id`=`project_profits`.`user_id` WHERE `project_profits`.`type`=1  GROUP BY `project_profits`.user_id ) g GROUP BY g.`second_broker_code`) b ON a.invite_code=b.second_broker_code LEFT JOIN
		(SELECT SUM(money) AS use_money, `user_info`.`second_broker_code` FROM `project_profits` LEFT JOIN `user_info` on `user_info` .`user_id`=`project_profits` .`user_id` where `project_profits` .`type`='1' GROUP BY `user_info`.`second_broker_code`) c ON a.invite_code=c.second_broker_code LEFT JOIN
		(SELECT SUM(money) AS invite_money,`projects_user`.`second_broker_code` FROM `project_profits` LEFT JOIN `projects_user`  on `projects_user`.`id` =`project_profits`.`project_user_id`WHERE  `project_profits`.`type` =2 AND `project_profits`.`role_slug` ='user' GROUP BY `projects_user`.second_broker_code ) d ON a.invite_code=d.second_broker_code LEFT JOIN
		(SELECT SUM(money) AS return_money, `projects_user`.`second_broker_code` from `project_profits` LEFT JOIN `projects_user` on `projects_user` .`id`=`project_profits`.`project_user_id` where `project_profits`.`type` =2 AND `project_profits`.`role_slug` ='agent' GROUP BY `projects_user`.`second_broker_code`) e ON a.invite_code=e.second_broker_code
		");
//        $one['name']='张三';
//        $one['invite_code']='ABCDEF';
//        $one['valid_num']='3';
//        $one['use_money']='100.00';
//        $one['invite_money']='10.00';
//        $one['return_money']='1.00';
//
//        $two['name']='李四';
//        $two['invite_code']='FEDCBA';
//        $two['valid_num']='4';
//        $two['use_money']='101.00';
//        $two['invite_money']='11.00';
//        $two['return_money']='2.00';
//        $list=array($one,$one,$one,$one,$two,$two,$two,$two,$one,$two,$one,$one,$one,$one,$two,$two,$two,$two,$one,$two);

        $all['invite_agent_url']=$this->getNowUrl().'/weixin/html/Ucenter/register-agent.html?code='.$user->userInfo->invite_code;
//        $all['invite_agent_url']='敬请期待';
        $all['use_money']=collect($list)->sum('use_money');
        $all['invite_money']=collect($list)->sum('invite_money');
        $all['return_money']=collect($list)->sum('return_money');

        $start=$page*8;
        $lists=collect($list)->sortByDesc('created_at')->slice($start,8);

        $content= view('api.u_agent',compact('lists'))->__toString();
        return $this->my_jsonp($request->input('callback'),compact('content','all'));
    }
    /*
     * 经济人-二级经纪人详情
     */
    public function secondAgentDetail(Request $request,$page,$code){
        $user=User::user();
        if(!$user->hasRole('Agent')){
            return $this->my_jsonp($request->input('callback'),'',600,'不具备对应的权限');
        }
        $second_broker_code=$code;

        $second_broker=User::leftJoin('user_info','user_info.user_id','=','users.id')->where('user_info.invite_code','=',$second_broker_code)->first();

        if($second_broker->invite_code==$second_broker->second_broker_code && $user->userInfo->invite_code==$second_broker->broker_code){

        $list=DB::select("SELECT a.username,a.user_id,a.phone_number,a.name,a.created_at,b.use_money,c.invite_money,d.return_money FROM
		(SELECT `user_info`.`created_at`,`user_info`.`user_id`,`users`.`username`,`users`.`phone_number`,`user_info`.`name`FROM `user_info` LEFT JOIN `users` on `user_info` .`user_id`=`users`.`id` WHERE `user_info`.`second_broker_code` = '".$second_broker->userInfo->invite_code."' ) a LEFT JOIN
		(SELECT SUM(money) AS use_money, `user_info`.`user_id` FROM `project_profits` LEFT JOIN `user_info` on `user_info` .`user_id`=`project_profits` .`user_id` where `project_profits` .`type`='1' GROUP BY `user_info`.`user_id`) b ON a.user_id=b.user_id LEFT JOIN
		(SELECT SUM(money) AS invite_money,`projects_user`.`user_id` FROM `project_profits` LEFT JOIN `projects_user`  on `projects_user`.`id` =`project_profits`.`project_user_id`WHERE  `project_profits`.`type` =2 AND `project_profits`.`role_slug` ='user' GROUP BY `projects_user`.user_id ) c ON a.user_id=c.user_id LEFT JOIN
		(SELECT SUM(money) AS return_money, `projects_user`.`user_id` from `project_profits` LEFT JOIN `projects_user` on `projects_user` .`id`=`project_profits`.`project_user_id` where `project_profits`.`type` =2 AND `project_profits`.`role_slug` ='agent' GROUP BY `projects_user`.`user_id`) d ON a.user_id=d.user_id
		");

//            $one['name']='张三';
//            $one['invite_code']='ABCDEF';
//            $one['created_at']='2016-01-01';
//            $one['use_money']='10.00';
//            $one['invite_money']='1.00';
//            $one['return_money']='2.00';
//
//            $two['name']='李四';
//            $two['invite_code']='FEDCBA';
//            $two['created_at']='2016-02-31';
//            $two['use_money']='11.00';
//            $two['invite_money']='1.10';
//            $two['return_money']='3.00';
//            $list=array($one,$one,$one,$one,$two,$two,$two,$two,$one,$two,$one,$one,$one,$one,$two,$two,$two,$two,$one,$two);

            $all['name']=$second_broker->name;
            $all['invite_code']=$second_broker_code;
            $all['use_money']=collect($list)->sum('use_money');
            $all['invite_money']=collect($list)->sum('invite_money');
            $all['return_money']=collect($list)->sum('return_money');

            $start=$page*8;
            $lists=collect($list)->sortByDesc('created_at')->slice($start,8);

            $content= view('api.u_agent_list',compact('lists'))->__toString();
            return $this->my_jsonp($request->input('callback'),compact('content','all'));
        }
        return '非法操作';
    }
}